package com.ershi.spring.aop.proxy.interceptor;

import com.ershi.spring.aop.proxy.common.TargetMethod;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 二十
 * @since 2021/11/1 12:13 上午
 */
public class JdkProxy implements InvocationHandler {

	Object target;

	List<MyInterceptor> interceptors = new ArrayList<>();

	public void add(MyInterceptor a) {
		interceptors.add(a);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		return new MyInvocationImpl(
				interceptors,
				new TargetMethod(
						target,
						method,
						args
				)
		).proceed();
	}

	public Object getProxy(){
		return Proxy.newProxyInstance(
				target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				this
		);
	}

	public JdkProxy(Object target) {
		this.target = target;
	}
}
